package main;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import io.summer.auth.tool.RsaTool;

import java.io.File;
import java.nio.file.Paths;
import java.util.Optional;

public class GenerateRsaKey {
  private static final String PROJECT_PATH = "/server/auth";
  private static final String PATH_TO_RESOURCES = "/src/main/resources";
  private static final int KEY_SIZE = 512;
  private static final String DEFAULT_PUB_NAME = "/rsa/auth-public-key.pub";
  private static final String DEFAULT_PRI_NAME = "/rsa/auth-private-key.pk";
  //NOTE: 修改这个secret为自己的rsa
  private static final String DEFAULT_SECRET = "summer-rsa";

  private static String getKeyPath(String root, String env, String defaultName) {
    String path = System.getenv(env);
    if (StrUtil.isBlank(path)) {
      return root + PATH_TO_RESOURCES + defaultName;
    }
    return Paths.get(path).isAbsolute() ? path : root + PATH_TO_RESOURCES + path;
  }

  private static String getSecret() {
    return Optional.ofNullable(System.getenv("KEY_SECRET")).orElse(DEFAULT_SECRET);
  }

  private static int getKeySize() {
    return Optional.ofNullable(System.getenv("KEY_SIZE"))
      .map(Integer::parseInt).orElse(KEY_SIZE);
  }

  public static void main(String[] args) throws Exception {
    String path = new File("").getAbsolutePath();
    if (!path.contains(PROJECT_PATH)) {
      path += PROJECT_PATH;
    }
    String p1 = getKeyPath(path, "PUB_KEY", DEFAULT_PUB_NAME);
    String p2 = getKeyPath(path, "PRI_KEY", DEFAULT_PRI_NAME);
    if (FileUtil.exist(p1) || FileUtil.exist(p2)) {
      System.out.println("No Generate RsaKey for key has already exists");
      return;
    }
    RsaTool.generateKey(
      p1,
      p2,
      getSecret(),
      getKeySize());
  }
}
